import { Map, View } from "ol";
import Tile from "ol/layer/Tile";
import OSM from "ol/source/OSM";
import XYZ from "ol/source/XYZ";
import TileDebug from "ol/source/TileDebug";
import TileGrid from "ol/tilegrid/TileGrid";
import { get as getProjection } from "ol/proj";
import * as extent from "ol/extent";
import { createXYZ } from "ol/tilegrid";

export * from "./libs/draw"; // 绘制
export * from "./libs/mark"; //标记

/**
 * 挂载
 * @param {*} dom
 */
export function mount(dom) {
  const maxZoom = 9; //最大层级
  const resolutions4326 = [];
  for (let z = 0; z <= maxZoom; z++) {
    resolutions4326[z] = 1.40625 / Math.pow(2, z + 1);
  }
  // 2. 定义 EPSG:4326 坐标系的原点（左上角：[-180°, 90°]）
  const origin4326 = [-180, 90];
  // 3. 创建适用于 EPSG:4326 的 TileGrid
  const tileGrid4326 = new TileGrid({
    resolutions: resolutions4326, // 核心参数：分辨率数组
    origin: origin4326, // 原点坐标（左上角）
    tileSize: 256, // 瓦片尺寸（像素）
    projection: "EPSG:4326", // 明确坐标系
    extent: [-180, -90, 180, 90], // EPSG:4326 全范围（可选）
  });

  const map = new Map({
    target: dom, // 绑定html元素
    layers: [
      new Tile({
        source: new XYZ({
          projection: "EPSG:4326",
          tileGrid: tileGrid4326,
          url: "http://localhost:8080/tdtStreetTms/tiles/{z}/{x}/{-y}.jpg",
          // tileUrlFunction: (zxy) => {
          //   if (!zxy) return null;
          //   let [z, x, y] = zxy;
          //   // TMS的Y坐标 = 2^z - 1 - XYZ的Y坐标
          //   const maxY = Math.pow(2, z) - 1;
          //   y = maxY - y;
          //   return `http://localhost:8080/tdtStreetTms/tiles/${z}/${x}/${y}.jpg`;
          // },
          crossOrigin: "anoymous",
          wrapX: true,
          zoom: 1,
          minZoom: 1,
          maxZoom: 1,
        }),
      }),
    ],
    view: new View({
      extent: [-180, -90, 180, 90],
      // 地图视图
      projection: "EPSG:4326", // 坐标系，有EPSG:4326和EPSG:3857
      center: [0, 0], // 深圳坐标
      zoom: 1, // 地图缩放级别（打开页面时默认级别）
    }),
  });
  return map;
}
